#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据管理器
负责系统所有数据的存储、读取和管理
"""

import os
from datetime import datetime, timedelta
import random

class DataManager:
    def __init__(self):
        self.data_file = "supply_chain_data.txt"
        self.data = {
            "procurement_orders": [],
            "inventory_items": [],
            "delivery_orders": [],
            "suppliers": [],
            "restaurants": [],
            "warehouses": []
        }
        self.load_data()
        
    def load_data(self):
        """从TXT文件加载数据"""
        try:
            if os.path.exists(self.data_file):
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    content = f.read().strip()
                    if content:
                        # 解析TXT格式数据
                        self._parse_txt_data(content)
        except Exception as e:
            print(f"加载数据失败: {e}")
            
    def save_data(self):
        """保存数据到TXT文件"""
        try:
            with open(self.data_file, 'w', encoding='utf-8') as f:
                # 写入数据到TXT格式
                self._write_txt_data(f)
        except Exception as e:
            print(f"保存数据失败: {e}")
            
    def _parse_txt_data(self, content):
        """解析TXT格式的数据"""
        lines = content.split('\n')
        current_section = None
        
        for line in lines:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
                
            if line.startswith('[') and line.endswith(']'):
                current_section = line[1:-1]
                continue
                
            if current_section and '|' in line:
                self._parse_data_line(current_section, line)
                
    def _parse_data_line(self, section, line):
        """解析数据行"""
        parts = [part.strip() for part in line.split('|')]
        
        if section == "suppliers":
            if len(parts) >= 5:
                supplier = {
                    "id": parts[0],
                    "name": parts[1],
                    "contact": parts[2],
                    "phone": parts[3],
                    "address": parts[4]
                }
                self.data["suppliers"].append(supplier)
                
        elif section == "restaurants":
            if len(parts) >= 4:
                restaurant = {
                    "id": parts[0],
                    "name": parts[1],
                    "address": parts[2],
                    "manager": parts[3]
                }
                self.data["restaurants"].append(restaurant)
                
        elif section == "warehouses":
            if len(parts) >= 5:
                warehouse = {
                    "id": parts[0],
                    "name": parts[1],
                    "address": parts[2],
                    "capacity": int(parts[3]),
                    "current_stock": int(parts[4])
                }
                self.data["warehouses"].append(warehouse)
                
        elif section == "inventory_items":
            if len(parts) >= 10:
                item = {
                    "id": parts[0],
                    "name": parts[1],
                    "category": parts[2],
                    "unit": parts[3],
                    "current_stock": int(parts[4]),
                    "min_stock": int(parts[5]),
                    "max_stock": int(parts[6]),
                    "unit_price": float(parts[7]),
                    "supplier_id": parts[8],
                    "warehouse_id": parts[9]
                }
                self.data["inventory_items"].append(item)
                
        elif section == "procurement_orders":
            if len(parts) >= 9:
                order = {
                    "id": parts[0],
                    "item_id": parts[1],
                    "item_name": parts[2],
                    "supplier_id": parts[3],
                    "quantity": int(parts[4]),
                    "unit_price": float(parts[5]),
                    "total_amount": float(parts[6]),
                    "order_date": parts[7],
                    "expected_delivery": parts[8],
                    "status": parts[9] if len(parts) > 9 else "待确认"
                }
                self.data["procurement_orders"].append(order)
                
        elif section == "delivery_orders":
            if len(parts) >= 9:
                # 解析商品列表
                items_str = parts[7] if len(parts) > 7 else ""
                items = []
                if items_str:
                    for item_str in items_str.split(';'):
                        if ':' in item_str:
                            item_parts = item_str.split(':')
                            if len(item_parts) >= 4:
                                items.append({
                                    "item_id": item_parts[0],
                                    "item_name": item_parts[1],
                                    "quantity": int(item_parts[2]),
                                    "unit_price": float(item_parts[3]),
                                    "amount": int(item_parts[2]) * float(item_parts[3])
                                })
                
                order = {
                    "id": parts[0],
                    "restaurant_id": parts[1],
                    "restaurant_name": parts[2],
                    "warehouse_id": parts[3],
                    "warehouse_name": parts[4],
                    "order_date": parts[5],
                    "delivery_date": parts[6],
                    "items": items,
                    "total_amount": float(parts[8]) if len(parts) > 8 else 0,
                    "delivery_cost": int(parts[9]) if len(parts) > 9 else 0,
                    "status": parts[10] if len(parts) > 10 else "待配送"
                }
                self.data["delivery_orders"].append(order)
                
    def _write_txt_data(self, f):
        """写入TXT格式数据"""
        f.write("# 智能餐饮供应链管理系统数据文件\n")
        f.write(f"# 更新时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
        
        # 写入供应商数据
        f.write("[suppliers]\n")
        f.write("# ID|名称|联系人|电话|地址\n")
        for supplier in self.data["suppliers"]:
            f.write(f"{supplier['id']}|{supplier['name']}|{supplier['contact']}|{supplier['phone']}|{supplier['address']}\n")
        f.write("\n")
        
        # 写入餐厅数据
        f.write("[restaurants]\n")
        f.write("# ID|名称|地址|经理\n")
        for restaurant in self.data["restaurants"]:
            f.write(f"{restaurant['id']}|{restaurant['name']}|{restaurant['address']}|{restaurant['manager']}\n")
        f.write("\n")
        
        # 写入仓库数据
        f.write("[warehouses]\n")
        f.write("# ID|名称|地址|容量|当前库存\n")
        for warehouse in self.data["warehouses"]:
            f.write(f"{warehouse['id']}|{warehouse['name']}|{warehouse['address']}|{warehouse['capacity']}|{warehouse['current_stock']}\n")
        f.write("\n")
        
        # 写入库存商品数据
        f.write("[inventory_items]\n")
        f.write("# ID|名称|分类|单位|当前库存|最小库存|最大库存|单价|供应商ID|仓库ID\n")
        for item in self.data["inventory_items"]:
            f.write(f"{item['id']}|{item['name']}|{item['category']}|{item['unit']}|{item['current_stock']}|{item['min_stock']}|{item['max_stock']}|{item['unit_price']}|{item['supplier_id']}|{item['warehouse_id']}\n")
        f.write("\n")
        
        # 写入采购订单数据
        f.write("[procurement_orders]\n")
        f.write("# ID|商品ID|商品名称|供应商ID|数量|单价|总金额|订单日期|预计送达|状态\n")
        for order in self.data["procurement_orders"]:
            f.write(f"{order['id']}|{order['item_id']}|{order['item_name']}|{order['supplier_id']}|{order['quantity']}|{order['unit_price']}|{order['total_amount']}|{order['order_date']}|{order['expected_delivery']}|{order['status']}\n")
        f.write("\n")
        
        # 写入配送订单数据
        f.write("[delivery_orders]\n")
        f.write("# ID|餐厅ID|餐厅名称|仓库ID|仓库名称|订单日期|配送日期|商品列表|总金额|配送费|状态\n")
        for order in self.data["delivery_orders"]:
            # 格式化商品列表
            items_str = ";".join([f"{item['item_id']}:{item['item_name']}:{item['quantity']}:{item['unit_price']}" for item in order.get('items', [])])
            f.write(f"{order['id']}|{order['restaurant_id']}|{order['restaurant_name']}|{order['warehouse_id']}|{order['warehouse_name']}|{order['order_date']}|{order['delivery_date']}|{items_str}|{order['total_amount']}|{order['delivery_cost']}|{order['status']}\n")
        f.write("\n")
            
    def clear_all_data(self):
        """清空所有数据"""
        self.data = {
            "procurement_orders": [],
            "inventory_items": [],
            "delivery_orders": [],
            "suppliers": [],
            "restaurants": [],
            "warehouses": []
        }
        self.save_data()
        
    def init_sample_data(self):
        """初始化示例数据"""
        self.clear_all_data()
        
        # 供应商数据
        suppliers = [
            {"id": "SUP001", "name": "新鲜蔬菜供应商", "contact": "张经理", "phone": "13800138001", "address": "北京市朝阳区"},
            {"id": "SUP002", "name": "优质肉类供应商", "contact": "李经理", "phone": "13800138002", "address": "北京市海淀区"},
            {"id": "SUP003", "name": "海鲜水产供应商", "contact": "王经理", "phone": "13800138003", "address": "北京市东城区"},
            {"id": "SUP004", "name": "调料香料供应商", "contact": "赵经理", "phone": "13800138004", "address": "北京市西城区"}
        ]
        
        # 餐厅数据
        restaurants = [
            {"id": "REST001", "name": "美味中餐厅", "address": "北京市朝阳区建国门", "manager": "陈经理"},
            {"id": "REST002", "name": "时尚西餐厅", "address": "北京市海淀区中关村", "manager": "刘经理"},
            {"id": "REST003", "name": "特色火锅店", "address": "北京市东城区王府井", "manager": "杨经理"},
            {"id": "REST004", "name": "精品日料店", "address": "北京市西城区金融街", "manager": "周经理"}
        ]
        
        # 仓库数据
        warehouses = [
            {"id": "WH001", "name": "中央仓库", "address": "北京市大兴区", "capacity": 10000, "current_stock": 6500},
            {"id": "WH002", "name": "北区仓库", "address": "北京市昌平区", "capacity": 5000, "current_stock": 3200},
            {"id": "WH003", "name": "南区仓库", "address": "北京市丰台区", "capacity": 5000, "current_stock": 2800}
        ]
        
        # 库存商品数据
        inventory_items = [
            {"id": "ITEM001", "name": "新鲜白菜", "category": "蔬菜", "unit": "公斤", "current_stock": 500, "min_stock": 100, "max_stock": 1000, "unit_price": 3.5, "supplier_id": "SUP001", "warehouse_id": "WH001"},
            {"id": "ITEM002", "name": "优质牛肉", "category": "肉类", "unit": "公斤", "current_stock": 200, "min_stock": 50, "max_stock": 500, "unit_price": 45.0, "supplier_id": "SUP002", "warehouse_id": "WH001"},
            {"id": "ITEM003", "name": "新鲜鲈鱼", "category": "海鲜", "unit": "公斤", "current_stock": 80, "min_stock": 20, "max_stock": 200, "unit_price": 28.0, "supplier_id": "SUP003", "warehouse_id": "WH002"},
            {"id": "ITEM004", "name": "精选大米", "category": "主食", "unit": "公斤", "current_stock": 800, "min_stock": 200, "max_stock": 1500, "unit_price": 6.5, "supplier_id": "SUP001", "warehouse_id": "WH001"},
            {"id": "ITEM005", "name": "新鲜土豆", "category": "蔬菜", "unit": "公斤", "current_stock": 300, "min_stock": 80, "max_stock": 600, "unit_price": 2.8, "supplier_id": "SUP001", "warehouse_id": "WH002"},
            {"id": "ITEM006", "name": "优质猪肉", "category": "肉类", "unit": "公斤", "current_stock": 150, "min_stock": 40, "max_stock": 400, "unit_price": 32.0, "supplier_id": "SUP002", "warehouse_id": "WH003"},
            {"id": "ITEM007", "name": "生抽酱油", "category": "调料", "unit": "瓶", "current_stock": 120, "min_stock": 30, "max_stock": 300, "unit_price": 8.5, "supplier_id": "SUP004", "warehouse_id": "WH001"},
            {"id": "ITEM008", "name": "新鲜虾仁", "category": "海鲜", "unit": "公斤", "current_stock": 60, "min_stock": 15, "max_stock": 150, "unit_price": 68.0, "supplier_id": "SUP003", "warehouse_id": "WH002"}
        ]
        
        # 采购订单数据
        procurement_orders = []
        for i in range(10):
            order_date = datetime.now() - timedelta(days=random.randint(1, 30))
            item = random.choice(inventory_items)
            quantity = random.randint(50, 200)
            order = {
                "id": f"PO{str(i+1).zfill(4)}",
                "item_id": item["id"],
                "item_name": item["name"],
                "supplier_id": item["supplier_id"],
                "quantity": quantity,
                "unit_price": item["unit_price"],
                "total_amount": quantity * item["unit_price"],
                "order_date": order_date.strftime("%Y-%m-%d"),
                "expected_delivery": (order_date + timedelta(days=random.randint(1, 7))).strftime("%Y-%m-%d"),
                "status": random.choice(["待确认", "已确认", "配送中", "已完成"])
            }
            procurement_orders.append(order)
            
        # 配送订单数据
        delivery_orders = []
        for i in range(8):
            order_date = datetime.now() - timedelta(days=random.randint(1, 15))
            restaurant = random.choice(restaurants)
            warehouse = random.choice(warehouses)
            items = random.sample(inventory_items, random.randint(2, 4))
            
            order_items = []
            total_amount = 0
            for item in items:
                quantity = random.randint(10, 50)
                amount = quantity * item["unit_price"]
                total_amount += amount
                order_items.append({
                    "item_id": item["id"],
                    "item_name": item["name"],
                    "quantity": quantity,
                    "unit_price": item["unit_price"],
                    "amount": amount
                })
            
            order = {
                "id": f"DO{str(i+1).zfill(4)}",
                "restaurant_id": restaurant["id"],
                "restaurant_name": restaurant["name"],
                "warehouse_id": warehouse["id"],
                "warehouse_name": warehouse["name"],
                "order_date": order_date.strftime("%Y-%m-%d"),
                "delivery_date": (order_date + timedelta(days=random.randint(1, 3))).strftime("%Y-%m-%d"),
                "items": order_items,
                "total_amount": total_amount,
                "delivery_cost": random.randint(50, 200),
                "status": random.choice(["待配送", "配送中", "已送达", "已完成"])
            }
            delivery_orders.append(order)
        
        # 保存数据
        self.data["suppliers"] = suppliers
        self.data["restaurants"] = restaurants
        self.data["warehouses"] = warehouses
        self.data["inventory_items"] = inventory_items
        self.data["procurement_orders"] = procurement_orders
        self.data["delivery_orders"] = delivery_orders
        
        self.save_data()
        
    # 采购订单相关方法
    def get_procurement_orders(self):
        return self.data["procurement_orders"]
        
    def add_procurement_order(self, order):
        self.data["procurement_orders"].append(order)
        self.save_data()
        
    def update_procurement_order(self, order_id, updated_order):
        for i, order in enumerate(self.data["procurement_orders"]):
            if order["id"] == order_id:
                self.data["procurement_orders"][i] = updated_order
                self.save_data()
                return True
        return False
        
    def delete_procurement_order(self, order_id):
        self.data["procurement_orders"] = [order for order in self.data["procurement_orders"] if order["id"] != order_id]
        self.save_data()
        
    # 库存相关方法
    def get_inventory_items(self):
        return self.data["inventory_items"]
        
    def add_inventory_item(self, item):
        self.data["inventory_items"].append(item)
        self.save_data()
        
    def update_inventory_item(self, item_id, updated_item):
        for i, item in enumerate(self.data["inventory_items"]):
            if item["id"] == item_id:
                self.data["inventory_items"][i] = updated_item
                self.save_data()
                return True
        return False
        
    def delete_inventory_item(self, item_id):
        self.data["inventory_items"] = [item for item in self.data["inventory_items"] if item["id"] != item_id]
        self.save_data()
        
    # 配送订单相关方法
    def get_delivery_orders(self):
        return self.data["delivery_orders"]
        
    def add_delivery_order(self, order):
        self.data["delivery_orders"].append(order)
        self.save_data()
        
    def update_delivery_order(self, order_id, updated_order):
        for i, order in enumerate(self.data["delivery_orders"]):
            if order["id"] == order_id:
                self.data["delivery_orders"][i] = updated_order
                self.save_data()
                return True
        return False
        
    def delete_delivery_order(self, order_id):
        self.data["delivery_orders"] = [order for order in self.data["delivery_orders"] if order["id"] != order_id]
        self.save_data()
        
    # 基础数据相关方法
    def get_suppliers(self):
        return self.data["suppliers"]
        
    def get_restaurants(self):
        return self.data["restaurants"]
        
    def get_warehouses(self):
        return self.data["warehouses"]
        
    def get_low_stock_items(self):
        """获取库存不足的商品"""
        low_stock_items = []
        for item in self.data["inventory_items"]:
            if item["current_stock"] <= item["min_stock"]:
                low_stock_items.append(item)
        return low_stock_items 